package leetcode.datastructure.str;

import java.util.HashMap;
import java.util.Map;

public class Program13RomanNumToInteger {

    public Program13RomanNumToInteger() {
    }


    public int romanToInt(String s) {
//        return person(s);
        return office(s);
    }


    public int office(String s) {
        char[] charArray = s.toCharArray();
        int count=0;
        int preNum=getValue(charArray[0]);
        for(int i=1;i<charArray.length;i++){
            int num=getValue(charArray[i]);
            if(preNum<num){
                count-=preNum;
            }else{
                count+=preNum;
            }
            preNum=num;

        }
        count+=preNum;
        return count;
    }
    private int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }


    public int person(String s) {
        Map<String, Integer> little = new HashMap<>();
        little.put("IV", 4);
        little.put("IX", 9);
        little.put("XL", 40);
        little.put("XC", 90);
        little.put("CD", 400);
        little.put("CM", 900);
        little.put("I", 1);
        little.put("V", 5);
        little.put("X", 10);
        little.put("L", 50);
        little.put("C", 100);
        little.put("D", 500);
        little.put("M", 1000);

        int res = 0;
        int length = s.length();
        for (int i = 0; i < length;) {
            if (i + 1 < length) {
                // 浪费时间多
                String substring = s.substring(i, i + 2);
                if (little.containsKey(s.substring(i, i + 2))) {
                    res += little.get(substring);
                    i += 2;
                    continue;
                }
            }
            res += little.get(s.substring(i, i + 1));
            i += 1;
        }
        return res;
    }


    public static void main(String[] args) {
        Program13RomanNumToInteger obj = new Program13RomanNumToInteger();
        System.out.println(obj.romanToInt("III"));
        System.out.println(obj.romanToInt("IV"));
        System.out.println(obj.romanToInt("IX"));
        System.out.println(obj.romanToInt("LVIII"));
        System.out.println(obj.romanToInt("MCMXCIV"));
    }
}
